#include "FileSender.h"
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#include <sys/time.h>

#define DEFAULT_IP "127.0.0.1"
#define DEFAULT_PORT 9001

 // 接口后续要跟FPGA的IO相连
 // 准确说是程序控制的arm核的某些IO口跟FPGA的IO相连
 // 需要注意接口的设计
 // 模拟4个PS发送数据时，需要按照一定的节奏，不能太快
 
int main(int argc, char* argv[]) {
    if (argc >= 7 && std::string(argv[5]) == "multiudp") {
        // 多文件多线程UDP模式
        std::vector<std::string> file_paths = {argv[1], argv[2], argv[3], argv[4]};
        std::string dest_ip = argv[6];
        int dest_port = (argc > 7) ? atoi(argv[7]) : DEFAULT_PORT;
        int local_port = (argc > 8) ? atoi(argv[8]) : 0;
        std::vector<std::thread> threads;
        struct timeval start, end;
        // 新增：启动指令监听线程
        std::thread cmd_thread(FileSender::waitForCommand);
        gettimeofday(&start, NULL);
        for (int i = 0; i < 4; ++i) {
            threads.emplace_back([=]() {
                FileSender sender(file_paths[i], dest_ip, dest_port, local_port);
                sender.sendUDP(i); // 传递文件编号
            });
        }
        for (auto& t : threads) t.join();
        cmd_thread.join();
        gettimeofday(&end, NULL);
        double elapsed = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
        std::cout << "Multi-file UDP send finished." << std::endl;
        std::cout << "Elapsed time: " << elapsed << " s" << std::endl;
        return 0;
    }
    // 单文件模式
    std::string file_path = "./data/test.bin";
    std::string dest_ip = DEFAULT_IP;
    int dest_port = DEFAULT_PORT;
    int local_port = 0;
    std::string protocol = "udp";
    if (argc > 1) file_path = argv[1];
    if (argc > 2) protocol = argv[2];
    if (argc > 3) dest_ip = argv[3];
    if (argc > 4) dest_port = atoi(argv[4]);
    if (argc > 5) local_port = atoi(argv[5]);

    struct timeval start, end;
    gettimeofday(&start, NULL);
    FileSender sender(file_path, dest_ip, dest_port, local_port);
    if (protocol == "udp") {
        sender.sendUDP();
    } else if (protocol == "tcp") {
        sender.sendTCP();
    } else {
        std::cerr << "Unknown protocol: " << protocol << std::endl;
        return 1;
    }
    gettimeofday(&end, NULL);
    double elapsed = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
    std::cout << "Send finished." << std::endl;
    std::cout << "Elapsed time: " << elapsed << " s" << std::endl;
    return 0;
} 